/*
 * Copyright (c) 2022  by Junzhao
 * THIS FILE IS PART OF JAVASE Song Huongkang PROJECT
 * All Rights Reserved.
 */

package 练习.生产者消费者;
/**
 * @description 经典的多线程问题
 * @author 俊昭
 * @date 2022/4/13
*/
public class ProductTest {
    public static void main(String[] args) {
        Clerk clerk =new Clerk();
        Producer p1 = new Producer(clerk,"生产者①");
        Consumer c1 = new Consumer(clerk,"消费者①");
//        Consumer c2 = new Consumer(clerk,"消费者②");
        p1.start();
        c1.start();
//        c2.start();
    }
}
class Clerk{// 店员
    private int productCount=0;

//    @Override
//    public void run() {
//
//    }
    /**
     * @description 生产产品
     * @author 俊昭
     * @date 2022/4/13
    */
    public synchronized void produceProduct() {
        notify();
        if (productCount<20){
            productCount++;
            System.out.println(Thread.currentThread().getName() + "开始生产第"+productCount+"个产品");
        }else{
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
    /**
     * @description 消费产品
     * @author 俊昭
     * @date 2022/4/13
     */
    public synchronized void consumeProduct() {
        notify();
        if (productCount>0){
            System.out.println(Thread.currentThread().getName() + "开始消费第"+productCount+"个产品");
            productCount--;
        }else{
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
class Producer extends Thread{// 生产者
    private Clerk clerk;
    public Producer(Clerk clerk,String s){
        this.clerk = clerk;
        this.setName(s);

    }

    @Override
    public void run() {
//        System.out.println(getName() + "开始生产产品");
        while (true){

            try {
                Thread.sleep((long) Math.random()*100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            clerk.produceProduct();
        }
    }
}
class Consumer extends Thread{// 消费者
    private Clerk clerk;

    public Consumer(Clerk clerk,String s){
        this.clerk = clerk;
        this.setName(s);
    }

    @Override
    public void run() {
//        System.out.println(getName() + "开始消费产品");
        for (;;){

            try {
                Thread.sleep((long) Math.random()*100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            clerk.consumeProduct();
        }
    }
}